//
//  GroupMemberViewController.m
//  Findif
//
//  Created by Mac on 2019/2/27.
//  Copyright © 2019年 Cicel Chen. All rights reserved.
//

#import "GroupMemberViewController.h"
#import "GroupMemberTableViewCell.h"
#import "MemberSearchHeaderView.h"
#import "MemberHeaderFooterView.h"
#import "MenuTableViewCell.h"
#import "GrayFooterView.h"
#import "MemberModel.h"
#import <JMessage/JMessage.h>
#import "SearchPersonViewController.h"
#import "SearchPersonModel.h"
#import "PersonalViewController.h"

@interface GroupMemberViewController ()<UITableViewDelegate,UITableViewDataSource,MemberSearchHeaderViewDelegate>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, weak)UIView * backView;
@property (nonatomic, weak)UITableView * menuView;
@property (nonatomic, strong)NSArray * titleArray;
@property (nonatomic, weak)UIButton * rightButton;
@property (nonatomic, weak)UIButton * leftButton;
@property (nonatomic, copy)NSString * state;
@property (nonatomic, strong)NSArray <MemberModel *> * memberList;
@property (nonatomic, copy)NSString * type;

@property (nonatomic, strong)NSArray <SearchPersonModel *> * searchArray;

@end

@implementation GroupMemberViewController


- (void)viewWillAppear:(BOOL)animated{
    
    [self loadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.titleArray = @[@"禁言",@"踢人"];
    self.state = @"back";
    
    [self setupNav];
    [self setupUI];
}


- (void)loadData{
    
    [[ZRNetworkTool sharedTool] getGroupMembersListWithGroup_id:self.group_id WithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"res===%@",responseData);
        if (success) {
            
            self.memberList = [NSArray yy_modelArrayWithClass:[MemberModel class] json:responseData[@"data"]];
        }
    }];
    
}


- (void)setMemberList:(NSArray<MemberModel *> *)memberList{
    
    _memberList = memberList;
    
    [self.tableView reloadData];
}


- (void)setupNav{
    
    self.title = @"社团成员";
    
    UIButton * leftButton = [[UIButton alloc] init];
    
    [leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(didCancelButton) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    leftButton.size = CGSizeMake(40 * SCREENH6, 30 * SCREENH6);
    
    self.leftButton = leftButton;
    
    UIBarButtonItem * leftBar = [[UIBarButtonItem alloc] initWithCustomView:self.leftButton];
    
    self.navigationItem.leftBarButtonItem = leftBar;
    
    UIButton * rightButton = [[UIButton alloc] init];
    
    [rightButton setImage:[UIImage imageNamed:@"成员更多"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didMoreButton) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitleColor:ZRBlackColor forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15 * SCREENH6];
    rightButton.size = CGSizeMake(40 * SCREENH6, 30 * SCREENH6);
    
    self.rightButton = rightButton;
    
    UIBarButtonItem * rightBar = [[UIBarButtonItem alloc] initWithCustomView:self.rightButton];
    
    self.navigationItem.rightBarButtonItem = rightBar;
    
    
    if ([self.identity isEqualToString:@"1"]) {
        
        self.rightButton.hidden = NO;
    }else{
        
        self.rightButton.hidden = YES;
    }
}

- (void)setupUI{
    
    self.view.backgroundColor = ColorWithRGB(0xF4F5F6);
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH) style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ColorWithRGB(0xF4F5F6);
//        tableView.rowHeight = 70 * SCREENH6;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.showsVerticalScrollIndicator = NO;
    
    MemberSearchHeaderView * headerView =  [[MemberSearchHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 50 * SCREENH6)];
    // 设置header
    headerView.delegate = self;
    
    tableView.tableHeaderView = headerView;
    
    self.tableView = tableView;
    
    [self.tableView registerClass:[GroupMemberTableViewCell class] forCellReuseIdentifier:@"GroupMemberTableViewCell"];
    [self.tableView registerClass:[MemberHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"MemberHeaderFooterView"];
    
    //    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
    //
    //        [self loadData];
    //    }];
    
    [self.view addSubview:self.tableView];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == self.tableView) {
        
        return 2;
    }else{
        
        return 2;
    }
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        if(section == 0){
            
            return 1;
        }else{
            
            return self.memberList.count - 1;
        }
    }else{
        
        if (section == 0) {
            
            return self.titleArray.count;
        }else{
            
            return 1;
        }
    }
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        
        GroupMemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GroupMemberTableViewCell" forIndexPath:indexPath];
        
        //    cell.model = self.goodlistArray[indexPath.row];
        if (indexPath.section == 0) {
            
            cell.memberModel = self.memberList[indexPath.row];
        }else{
            
            cell.memberModel = self.memberList[indexPath.row + 1];
        }
        
        return cell;
    }else{
        
        MenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MemberMenuTableViewCell" forIndexPath:indexPath];
        
        if (indexPath.section == 0) {
            
            cell.showLabel.text = self.titleArray[indexPath.row];
        }else{
            
            cell.showLabel.text = @"取消";
        }
        
        
        return cell;
    }
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        
        if (indexPath.section == 1) {
            
            ShowHUD;
            MemberModel * model = self.memberList[indexPath.row + 1];
            NSString * user_id = [NSString stringWithFormat:@"%@",model.user_id];
            if ([self.type isEqualToString:@"delete"]) {
                
                NSDictionary * dict = @{@"group_id":self.group_id,@"removed_user_id":user_id};
                [[ZRNetworkTool sharedTool] deleteGroupMembersWithDict:dict WithBlock:^(BOOL success, id responseData) {
                    
//                    NSLog(@"res===%@",responseData);
                    HiddenHUD;
                    if (success) {
                        
                        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:responseData[@"message"]
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                              handler:^(UIAlertAction * action) {
                                                                                  [self loadData];
                                                                                  self.state = @"back";
                                                                                  
                                                                                  [self.leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
                                                                                  [self.leftButton setTitle:@"" forState:UIControlStateNormal];
                                                                                  [self.rightButton setImage:[UIImage imageNamed:@"成员更多"] forState:UIControlStateNormal];
                                                                                  [self.rightButton setTitle:@"" forState:UIControlStateNormal];
                                                                              }];
                        
                        [alert addAction:defaultAction];
                        [self presentViewController:alert animated:YES completion:nil];
                        
                    }else{
                        
                        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:responseData[@"message"]
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                              handler:^(UIAlertAction * action) {
                                                                                  
                                                                              }];
                        
                        [alert addAction:defaultAction];
                        [self presentViewController:alert animated:YES completion:nil];
                    }
                }];
            }else if ([self.type isEqualToString:@"shut"]){
                
//                NSString * phone = [NSString stringWithFormat:@"%@",model.phone];
                int is_banned = [model.is_banned intValue];
//                JMSGConversation * conversation = [JMSGConversation groupConversationWithGroupId:self.group_jg_gid];
//
//                JMSGGroup * group = conversation.target;
//
//                [group setGroupMemberSilence:YES username:phone appKey:@"e247c401cfa87e24fd2ab961" handler:^(id resultObject, NSError *error) {
//
//                    NSLog(@"res===%@",resultObject);
//                    NSLog(@"error===%@",error);
//
//                }];
//                //禁言   0 否  1 是
                if (is_banned == 1) {
                    
                    NSDictionary * dict = @{@"group_id":self.group_id,@"user_id":user_id,@"is_banned":@"0"};
                    [self bannedGroupMemberWithDict:dict];
                    
                }else if (is_banned == 0){
                    
                    NSDictionary * dict = @{@"group_id":self.group_id,@"user_id":user_id,@"is_banned":@"1"};
                    [self bannedGroupMemberWithDict:dict];
                    
                }
                
            }else{
                
                HiddenHUD;
                
                NSString * user_id = [NSString stringWithFormat:@"%@",model.user_id];
                NSString * ID = DEF_GET_OBJECT(@"id");
                if ([user_id isEqualToString:ID]) {
                    
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                   message:@"亲，不能点击自己"
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                          handler:^(UIAlertAction * action) {
                                                                              
                                                                          }];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                }else{
                    
                    HiddenBar;
                    PersonalViewController * personVC = [PersonalViewController new];
                    
                    personVC.ID = user_id;
                    
                    [self.navigationController pushViewController:personVC animated:YES];
                }
                
            }
        }

    }else{
        
        if (indexPath.section == 0) {
            
            if (indexPath.row == 0) {
                
                self.type = @"shut";
                [self.rightButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [self.rightButton setTitle:@"禁言" forState:UIControlStateNormal];
            }else{
                
                self.type = @"delete";
                [self.rightButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
                [self.rightButton setTitle:@"踢人" forState:UIControlStateNormal];
            }
            
            self.state = @"cancel";
            [self.leftButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
            [self.leftButton setTitle:@"取消" forState:UIControlStateNormal];
        }
        
        [self removeMenuView];
    }
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        
        return 70 * SCREENH6;
    }else{
        
        return 40 * SCREENH6;
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        return 30 * SCREENH6;
    }else{
        
        return 0;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        
        MemberHeaderFooterView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MemberHeaderFooterView"];
        
        if (section == 0) {
            
            header.titleLabel.text = @"社长（1人）";
        }else{
            
            header.titleLabel.text = [NSString stringWithFormat:@"社团成员（%lu人）",self.memberList.count - 1];
        }
        return header;
    }else{
        
        return nil;
    }
    
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        return nil;
    }else{
        
        if (section == 0) {
            
            GrayFooterView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"MemberGrayFooterView"];
            
            return header;
        }else{
            
            return nil;
        }
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        return 0;
    }else{
        
        if (section == 0) {
            
            return 20 * SCREENH6;
        }else{
            
            return 0;
        }
    }
    
}


- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    
    if (tableView == self.tableView) {
        
        if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
            ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ColorWithRGB(0xF4F5F6);
        }
    }
    
}


- (void)didMoreButton{
    
    [self didMenuButton];
}


- (void)didMenuButton{
    
    UIView * backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    backView.backgroundColor = ZRBlackColor;
    backView.alpha = 0.4;
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeMenuView)];
    backView.userInteractionEnabled = YES;
    [backView addGestureRecognizer:tapGR];
    
    self.backView = backView;
    
    [self.tabBarController.view addSubview:self.backView];
    
    
    UITableView * menuView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScreenH - kBarHeight - 140 * SCREENH6, kScreenW, 140 * SCREENH6)];
    
    menuView.delegate = self;
    menuView.dataSource = self;
    menuView.backgroundColor = ZRWhiteColor;
    menuView.separatorStyle = UITableViewCellSeparatorStyleNone;
    menuView.showsVerticalScrollIndicator = NO;
    
    self.menuView = menuView;
    
    [self.menuView registerClass:[MenuTableViewCell class] forCellReuseIdentifier:@"MemberMenuTableViewCell"];
    [self.tableView registerClass:[GrayFooterView class] forHeaderFooterViewReuseIdentifier:@"MemberGrayFooterView"];
    
    [self.tabBarController.view addSubview:self.menuView];
}

- (void)didCancelButton{
    
    if ([self.state isEqualToString:@"back"]) {
        
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        
        self.state = @"back";
        
        [self.leftButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [self.leftButton setTitle:@"" forState:UIControlStateNormal];
        [self.rightButton setImage:[UIImage imageNamed:@"成员更多"] forState:UIControlStateNormal];
        [self.rightButton setTitle:@"" forState:UIControlStateNormal];
    }
}

- (void)removeMenuView{
    
    [self.backView removeFromSuperview];
    [self.menuView removeFromSuperview];
}

- (void)bannedGroupMemberWithDict:(NSDictionary *)dict{
    
    [[ZRNetworkTool sharedTool] bannedGroupMemberWithDict:dict WithBlock:^(BOOL success, id responseData) {
        HiddenHUD;
        if (success) {
            
            [self loadData];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}


- (void)getSearchString:(NSString *)str{

    ShowHUD;

    NSDictionary * dict = @{@"group_id":self.group_id,@"search_str":str};
    
    [[ZRNetworkTool sharedTool] selectGroupMembersWithDict:dict WithBlock:^(BOOL success, id responseData) {
        
        HiddenHUD;
        if (success) {
            
            self.searchArray = [NSArray yy_modelArrayWithClass:[SearchPersonModel class] json:responseData[@"data"]];
            
            HiddenBar;
            SearchPersonViewController * searchVC = [SearchPersonViewController new];
            
            searchVC.modelArray = self.searchArray;
            
            [self.navigationController pushViewController:searchVC animated:YES];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}


@end
